package com.atguigu.guli.service.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.guli.service.edu.entity.Subject;
import com.atguigu.guli.service.edu.entity.excel.SubjectData;
import com.atguigu.guli.service.edu.mapper.SubjectMapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

public class SubjectDataListener extends AnalysisEventListener<SubjectData> {
    SubjectMapper subjectMapper;
    public SubjectDataListener(SubjectMapper subjectMapper){
        this.subjectMapper=subjectMapper;
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        //每次读取一行数据会被调用一次，将本次的数据存到数据库中
        String levelOneSubjectTitle = subjectData.getLevelOneSubjectTitle();//拿到标题
        String levelTwoSubjectTitle = subjectData.getLevelTwoSubjectTitle();

        //判断如果一级分类没有，保存一级课程分类
        LambdaQueryWrapper<Subject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Subject::getParentId,"0");
        queryWrapper.eq(Subject::getTitle,levelOneSubjectTitle);
        Subject psubject = subjectMapper.selectOne(queryWrapper);
        if (psubject==null){
            psubject = new Subject();
            psubject.setParentId("0");
            psubject.setTitle(levelOneSubjectTitle);
            psubject.setSort(0);
            subjectMapper.insert(psubject);
        }

        //判断如果当前一级分类的二级分类不存在，保存二级课程分类
        queryWrapper.clear();
        queryWrapper.eq(Subject::getTitle,levelTwoSubjectTitle);
        queryWrapper.eq(Subject::getParentId,psubject.getId());

        Integer count = subjectMapper.selectCount(queryWrapper);
        if (count==0){
            Subject subject=new Subject();
            subject.setSort(0);
            subject.setTitle(levelTwoSubjectTitle);
            subject.setParentId(psubject.getId());
            subjectMapper.insert(subject);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.println("excel文档解析已完成");
    }
}
